<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic;


use app\common\model\Card;
use app\common\model\CommissionLog;
use app\common\model\ImeiSearch;
use app\common\model\InsuranceOrder;
use app\common\model\InsurancePolicy;
use app\common\logic\BaseLogic;
use app\common\model\Product;
use app\common\model\user\User;
use app\common\service\pay\WeChatPayService;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;


/**
 * InsurancePolicy逻辑
 * Class InsurancePolicyLogic
 * @package app\adminapi\logic
 */
class InsurancePolicyLogic extends BaseLogic
{


    /**
     * @param $insurancePolicyId
     * @param int $applyStatus
     * @notes 审核
     * @return bool
     */
    public static function apply($insurancePolicyId, int $applyStatus): bool
    {
        $insuranceOrder = InsuranceOrder::findOrEmpty($insurancePolicyId);
        if ($insuranceOrder->pay_status != InsuranceOrder::STATUS_PAY) {
            self::setError('保单状态异常');
            return false;
        }

        Db::startTrans();

        try {
            if ($applyStatus == 1) {
                InsurancePolicy::where('order_no', $insuranceOrder->order_no)->update(['status' => InsurancePolicy::STATUS_EFFECTIVE]);
                $insuranceOrder->insurance_policy_status = InsurancePolicy::STATUS_EFFECTIVE;
                // 激活卡密 发放佣金
                if ($insuranceOrder->card_pwd) {
                    $card = Card::where('account', $insuranceOrder->card_pwd)->findOrFail();
                    $card->status = 1;
                    $card->user_id = $insuranceOrder->user_id;
                    $card->save();
                    if ($card->merchant_id) {
                        // 计算商家佣金
                        CommissionLog::log($card->merchant, bcmul($insuranceOrder->order_amount, $card->merchant->proportion, 2),
                            '激活卡片获得佣金' . $insuranceOrder->order_no);
                    }

                }
            } else {
                InsurancePolicy::where('order_no', $insuranceOrder->order_no)->update(['status' => InsurancePolicy::STATUS_REFUND]);
                $insuranceOrder->insurance_policy_status = InsurancePolicy::STATUS_REFUND;
                $insuranceOrder->pay_status = InsuranceOrder::STATUS_REFUND;

                $refundNo = generate_sn(InsuranceOrder::class, 'refund_no');

                //todo 拒绝后退款
                if ($insuranceOrder->pay_type == 2) {
                    //todo 微信退款
                    $refundRes = (new WeChatPayService(2))->refund([
                        'transaction_id' => $insuranceOrder->transaction_id,
                        'refund_sn'      => $refundNo,
                        'refund_amount'  => $insuranceOrder->order_amount,// 退款金额
                        'total_amount'   => $insuranceOrder->order_amount,// 订单金额
                    ]);
                    if ($refundRes['status'] === 'ABNORMAL') {
                        self::setError('微信退款失败');
                        return false;
                    }
                }
            }
            $insuranceOrder->save();
            Db::commit();
            return true;
        } catch (\Exception  $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }


    }

    public static function addUserInsurancePolicy(
        User $user,
        string $imei,
        array $product_id_arr,
        string $card_pwd = '',
        array $imgs = [],
        string $contacts_name = '',
        string $contacts_phone = '',
        string $signImg = ''
    ): InsuranceOrder|bool {

        if ($card_pwd){
            /**
             * @var Card $card
             */
            $card = Card::where('account', $card_pwd)->find();
            if (!$card) {
                self::setError('卡密不存在');
                return false;
            }
            if ($card->status == 1) {
                self::setError('卡密已被使用');
                return false;
            }
        }
        $insuranceOrder = Db::transaction(function () use ($user ,$imei, $product_id_arr, $card_pwd, $imgs, $contacts_name, $contacts_phone,$signImg) {

            $orderNo = generate_sn(InsuranceOrder::class, 'order_no','',4,'',strtotime($user->create_time));
            $productList = Product::whereIn('id', $product_id_arr)->select();
            $totalPrice = array_sum($productList->column('price'));
            $insuranceOrder = new InsuranceOrder();
            $insuranceOrder->user_id = $user->id;
            $insuranceOrder->order_no = $orderNo;
            $insuranceOrder->order_amount = $totalPrice;
            $insuranceOrder->sign_img = $signImg;
            $insuranceOrder->imei = $imei;
            $insuranceOrder->imgs = json_encode($imgs);
            $insuranceOrder->card_pwd = $card_pwd;
            $insuranceOrder->pay_type = 1;
            $insuranceOrder->contacts_name = $contacts_name;
            $insuranceOrder->contacts_phone = $contacts_phone;
            $insuranceOrder->save();

//            $imeiSearchRes  = ImeiSearch::where('imei', $imei)->findOrFail();

            $diskArr = [
                '64G',
                '128G',
                '256G',
                '512G',
                '1T',
            ];

           $disk =$diskArr[array_rand($diskArr)];

            $productList->each(function (Product $product) use ($user, $orderNo,$disk) {
                /**
                 * @var InsurancePolicy $insurancePolicy
                 */
                $insurancePolicy = new InsurancePolicy();

                $insurancePolicy->name = $product->name;
                $insurancePolicy->img = $product->img;
                $insurancePolicy->price = $product->price;
                $insurancePolicy->spec = $product->modelinfo->spec;
                $insurancePolicy->brand = $product->modelinfo->brand;
                $insurancePolicy->disk = $disk;
                $insurancePolicy->total_num = $product->num;
                $insurancePolicy->user_id = $user->id;
                $insurancePolicy->order_no = $orderNo;
                $insurancePolicy->status = InsurancePolicy::STATUS_WAIT_PAY;
                $insurancePolicy->start_date = $user->create_time;
                $insurancePolicy->end_date = date('Y-m-d', strtotime("+{$product->year} year",strtotime($user->create_time)));
                $insurancePolicy->left_num = $product->num;
                $insurancePolicy->product_type_id = $product->product_type_id;
                $insurancePolicy->save();
            });
            return $insuranceOrder;
        });

        return $insuranceOrder;
    }


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 14:05
     */
    public static function add(array $params): bool
    {
        self::addUserInsurancePolicy(User::findOrEmpty($params['user_id']), $params['imei'], [$params['product_id']], $params['card_pwd'],
            $params['imgs'] ?? []);
        return true;
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 14:05
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            InsurancePolicy::where('id', $params['id'])->update([
                'name'         => $params['name'],
                'img'          => $params['img'],
                'status'       => $params['status'],
                'total_num'    => $params['total_num'],
                'start_date'   => $params['start_date'],
                'end_date'     => $params['end_date'],
                'user_id'      => $params['user_id'],
                'card_account' => $params['card_account'],
                'card_pwd'     => $params['card_pwd'],
                'order_no'     => $params['order_no'],
                'merchant_id'  => $params['merchant_id'],
                'left_num'     => $params['left_num'],
                'price'        => $params['price'],
                'spec'         => $params['spec'],
                'brand'        => $params['brand'],
                'check_status' => $params['check_status'],
                'imgs'         => $params['imgs'],
                'imei'         => $params['imei']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 14:05
     */
    public static function delete(array $params): bool
    {
        return InsurancePolicy::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/02/14 14:05
     */
    public static function detail($params): array
    {
        return InsurancePolicy::findOrEmpty($params['id'])->toArray();
    }
}